package com.hmdp.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmdp.config.RedissonConfig;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {


    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private RedissonClient redissonClient;

    @Resource
    private RabbitTemplate rabbitTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    /**
     * 创建订单
     *
     * @param voucherOrder
     */
    public void handleVoucherOrder(VoucherOrder voucherOrder) {

        Long voucherId = voucherOrder.getVoucherId();
        //2.扣减库存
        boolean success = seckillVoucherService.update().setSql("stock=stock-1")
                .eq("voucher_id", voucherId)
                //======判断当前库存是否大于0就可以决定是否能抢池子中的券了
                .gt("stock", 0)
                .update();
        //3.创建订单
        save(voucherOrder);

    }

    @Override
    public Result seckillVoucher(Long voucherId) {
// 1、执行Lua脚本，判断用户是否具有秒杀资格
        Long result = null;
        try {
            result = stringRedisTemplate.execute(
                    SECKILL_SCRIPT,
                    Collections.emptyList(),
                    voucherId.toString(),
                    UserHolder.getUser().getId().toString()
            );
        } catch (Exception e) {
            log.error("Lua脚本执行失败");
            throw new RuntimeException(e);
        }
        if (result != null && !result.equals(0L)) {
            // result为1表示库存不足，result为2表示用户已下单
            int r = result.intValue();
            if(r==1){
               return Result.fail("库存不足");

            }
            if(r==4){
               return Result.fail("库存键不存在");
            }

            return Result.fail(r == 2 ? "不能重复下单" : "库存不足");
        }
        // 2、result为0，用户具有秒杀资格，将订单保存到阻塞队列中，实现异步下单
        long orderId = redisIdWorker.nextId("order");
        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId( UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
         //将订单保存到队列中

        rabbitTemplate.convertAndSend("seckill.direct","seckill.order",voucherOrder);
//        orderTasks.add(voucherOrder);
         //索取锁成功，创建代理对象，使用代理对象调用第三方事务方法， 防止事务失效
//        IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//        this.proxy = proxy;
        return Result.ok(orderId);













//
//        // 1、查询秒杀券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        // 2、判断秒杀券是否合法
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            // 秒杀券的开始时间在当前时间之后
//            return Result.fail("秒杀尚未开始");
//        }
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            // 秒杀券的结束时间在当前时间之前
//            return Result.fail("秒杀已结束");
//        }
//        if (voucher.getStock() < 1) {
//            return Result.fail("秒杀券已抢空");
//        }
//        Long userId= UserHolder.getUser().getId();//threadlocal
//        //获取锁
//        //SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "order" + userId);
//        RLock lock = redissonClient.getLock("lock:order" + userId);
//        //获取锁
//        boolean isLock = lock.tryLock();
//        if(!isLock) {
//            //获取锁失败，
//            return Result.fail("不允许重复下单,一人只允许下一单");
//        }
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            //释放锁
//            lock.unlock();
//        }
////        synchronized (userId.toString().intern()) {
////            IVoucherOrderService proxy =(IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(voucherId);
////        }

    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        //一人一单
        Long userId= UserHolder.getUser().getId();//threadlocal
            //查询订单
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            //判断是否存在
            if (count > 0) {
                //用户已经购买
                return Result.fail("用户已经购买");
            }

            // 5、秒杀券合法，则秒杀券抢购成功，秒杀券库存数量减一
            boolean flag = seckillVoucherService.update()
                    .setSql("stock = stock -1")  //set stock=stock-1
                    .eq("voucher_id", voucherId).gt("stock", 0)  //where id=? and stock>0
                    .update();

            if (!flag) {
                throw new RuntimeException("库存不足");
            }
            // 6、秒杀成功，创建对应的订单，并保存到数据库
            VoucherOrder voucherOrder = new VoucherOrder();//订单对象
            //6.1订单ID
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);
            //6.2用户ID
            voucherOrder.setUserId(userId);
            //6.3代金卷ID
            voucherOrder.setVoucherId(voucherId);
            save(voucherOrder);
            // 返回订单id
            return Result.ok(orderId);

    }
}
